<template>
  <div>
    <el-upload
        list-type="picture-card"
        :action="appBaseUrl + '/sysFile/upload'"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :on-preview="handlePreview"
        :on-exceed="handleExceed"
        :before-upload="beforeUpload"
        :on-error="handleError"
        :file-list="fileList"
        :limit="limit">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
function defaultBeforeUpload(file) {
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    this.$message.error('上传图片大小不能超过 2MB!');
  }
  return isLt2M;
}
export default {
  name: "MoreImgUpload",
  props: {
    value: {
      type: String,
      default: ''
    },
    limit:{
      type: Number,
      default: 6
    },
    beforeUpload:{
      type: Function,
      default: defaultBeforeUpload
    }
  },
  data() {
    return {
      dialogVisible:  false,
      dialogImageUrl : '',
      fileList:  []
    };
  },
  created() {
    this.fileList = this.value ? JSON.parse(this.value) : []
  },
  methods: {
    handleRemove(file, files) {
      this.fileList = files.map(item => {
        return {
          url: item.url
        }
      })
      this.$emit('input', this.fileList.length == 0 ? '' : JSON.stringify(this.fileList))
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true;
    },
    handleSuccess(res, file) {
      this.fileList.push({url: res})
      this.$message.success("上传成功")
      this.$emit('input', JSON.stringify(this.fileList))
    },
    handleError() {
      this.$message.error('上传失败!');
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 6 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    }
  },
  watch:{
    value(val) {
      this.fileList = val ? JSON.parse(val) : []
    }
  }
}
</script>

<style scoped>

</style>
